// Import modules
var gameFuncs = require('./game.js');
var herosFuncs = require('../DAO/schemaHero.js');
var grid = require('./grid.js');
var User = require('../DAO/schemaUser.js').User;
var Hero = require('../DAO/schemaHero.js').Hero;
var Map = require('../DAO/schemaMap.js').Map;

var gv = require('../globalVars.js').gv;

var allClients = [];

// Initialisation des variables et events
function events(socket, io){
    gameFuncs.tryPopulateMap();
    allClients.push(socket);

//    console.log('cur socket : ');
//    console.log(socket.id);
//    console.log('all clients : ');
//    for(var c in allClients) {
//        console.log(allClients[c].id);
//    }

    //TODO empêcher login du même user plusieurs fois (var connected in userSchema)
    // Un utilisateur s'identifie
    socket.on('cl_login', function(username, password) {
        login(socket, username, password, function(res){
            if (res == true){
                gameFuncs.startGame(socket, username);
                io.sockets.emit('sv_newusr', username);
            }
            else {
                console.log('wrong username / password or already connected');
            }
        });
    })

    // Un utilisateur se déconnecte
    socket.on('disconnect', function(){
        var i = allClients.indexOf(socket);
        io.sockets.emit('sv_delusr', allClients[i].name);
        console.log('deleting user with name : '+allClients[i].name);
        delete allClients[i];
    })

    socket.on('cl_registration', function(username, password){
        registration(username, password, function(){
            socket.emit('sv_registered');
        })
    })
}

function login(socket, username, password, callback){
    var result = false;
    User.find({username: username, password: password}, function(err, users) {
        if(err) {
            console.log(err);
        } else if (users.length == 1) {
            var i = allClients.indexOf(socket);
            allClients[i].name = users[0].username;
            result = true;
        }
        callback(result);
    });
}

function registration(username, password, callback){
    var newHero = newHeroInGame(username, function(hero) {
        var newUser = new User({username: username, password: password});
        if(hero == null) console.log('--- Error initialising hero for user '+username+' ---');
        newUser.setHero(hero);
        newUser.save(function (err){
            if (err){
                console.log ('--- registration() : Error on save --> ' + err.message + ' ---');
            } else {
                console.log('--- registration() : User '+newUser.username+' saved ! ---');
                callback();
            }
        });
    });
}

function newHeroInGame(username, callback) {
    var newHero = new Hero({name: "hero_" + username, gold : gv.playerStartGold});

    //on retourne la Map actuelle
    var curMap = null;
    var q = Map.find();
        q.exec(function(err, maps){
            if(err) {
                console.log('--- newHero() MAP search err: '+err.message+' ---');
                return null;
            }
            else if (maps.length > 0) {
                curMap = maps[0];

                //On save le nouveau héros avant d'appeler les fonctions pour placer sa zone sur la map
                newHero.save(function (err){
                    if (err){
                        console.log ('--- newHero() : Error on save hero : ' + err.message+' ---');
                    } else {
                        console.log('--- newHero() : Hero '+newHero.name+' (golds : '+newHero.gold+') saved ! ---');
                        //On set le héros (pos & territoire) sur la map courrante
                        grid.newPlayerOnMap(curMap,newHero);

                        callback(newHero);
                        return;
                    }
                });
            }
            else {
                console.log('map not found ( newHero() )');
                return null;
            }
        });
}


exports.events = events;